// handlers/folder_handlers.go
package handlers

import (
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/google/uuid"

	"file-manager/models"
	"file-manager/storage"
	"file-manager/utils"
)

type FolderHandlers struct{}

var Folder_Handlers = &FolderHandlers{}

// CreateFolder handles POST /api/folders (创建文件夹)
func (h *FolderHandlers) CreateFolder(c *gin.Context) {
	var req struct {
		Name   string `json:"name"`
		Parent string `json:"parent"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
		return
	}

	if req.Parent == "" {
		req.Parent = "root"
	}

	safeName := utils.SanitizeFilename(req.Name)
	if safeName == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid folder name"})
		return
	}

	// Check if folder already exists
	existing := storage.FindFileByNameAndParent(safeName, req.Parent)
	if existing != nil {
		c.JSON(http.StatusConflict, gin.H{"error": "Folder already exists"})
		return
	}

	folderID := uuid.New().String()
	newFolder := &models.File{
		ID:        folderID,
		Name:      safeName,
		Size:      0,
		Type:      "folder",
		Parent:    req.Parent,
		CreatedAt: time.Now(),
		UpdatedAt: time.Now(),
		Path:      "",
	}

	storage.AddFile(newFolder)

	c.JSON(http.StatusOK, gin.H{"folder": newFolder})
}
